<template>
  <div class="login">
    <h2>登录</h2>
    <form @submit.prevent="handleLogin">
      <div>
        <label for="account">账号：</label>
        <input
            type="text"
            v-model="account"
            id="account"
            placeholder="请输入账号"
            required
        />
      </div>
      <div>
        <label for="password">密码：</label>
        <input
            type="password"
            v-model="password"
            id="password"
            placeholder="请输入密码"
            required
        />
      </div>
      <button type="submit">登录</button>
    </form>
    <p v-if="error" class="error">{{ error }}</p>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      account: '18582542586',
      password: '1',
      error: null,
    };
  },
  methods: {
    async handleLogin() {
      try {
        const response = await axios.post('order/api/user/login', {
          account: this.account,
          password: this.password,
        });
        if (response.data.code === 200) {
          // 登录成功，保存 token 到 localStorage
          const token = response.data.data.token;
          localStorage.setItem('authToken', token);

          console.log('登录成功，token:', token);
          // 你可以在这里导航到主页或其他页面
          this.$router.push('/personal-center');
        } else {
          this.error = response.data.message || '登录失败';
        }
      } catch (err) {
        console.error('登录失败:', err);
        this.error = '登录失败，请检查账号或密码';
      }
    },
  },
};
</script>

<style scoped>
.login {
  max-width: 400px;
  margin: 0 auto;
  padding: 20px;
  border: 1px solid #ccc;
  border-radius: 4px;
}

label {
  display: block;
  margin-bottom: 8px;
}

input {
  width: 100%;
  padding: 8px;
  margin-bottom: 16px;
  border: 1px solid #ccc;
  border-radius: 4px;
}

button {
  padding: 10px 20px;
  background-color: #4CAF50;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

button:hover {
  background-color: #45a049;
}

.error {
  color: red;
  margin-top: 10px;
}
</style>
